package com.xoa.controller.workflow;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.xoa.model.workflow.TMacroCtrl;
import com.xoa.service.WFE.WFELog.WFELog;
import com.xoa.service.workflow.flowformtype.FlowFormService;
import com.xoa.service.workflow.wrapper.FlowFormWrappers;
import com.xoa.util.AjaxJson;
import com.xoa.util.CookiesUtil;
import com.xoa.util.EncodeUtil;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.common.wrapper.BaseWrapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xoa.model.workflow.FlowFormType;
import com.xoa.service.workflow.flowtype.FlowFormTypeService;
import com.xoa.util.ToJson;
import com.xoa.util.dataSource.ContextHolder;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;

@Controller
@Scope(value = "prototype")
@RequestMapping("/form")
public class FlowFormTypeController {
	@Resource
	private FlowFormTypeService  flowFormTypeService;
	@Autowired
	FlowFormService flowFormService;

	@Autowired
	private WFELog wfeLog;




	@RequestMapping(value = "formType",produces = {"application/json;charset=UTF-8"})
	public @ResponseBody ToJson<FlowFormType> qureyItemMax(@RequestParam("fromId") String fromId,HttpServletRequest request){
		Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
		return flowFormTypeService.qureyItemMax(Integer.parseInt(fromId));
	}
	@RequestMapping("/designer")
	public String designer(Model model,HttpServletRequest request, Integer formId) {
		Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);
		model.addAttribute("formId",formId);
		return "app/workflow/formtype/formDesigner";
	}
	@RequestMapping("/previews")
	public String previews(Model model,HttpServletRequest request,Integer formId) {
		Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        String loginDateSouse = SessionUtils.getSessionInfo(request.getSession(), "loginDateSouse", String.class, redisSessionCookie);
        ContextHolder.setConsumerType("xoa" + loginDateSouse);

		model.addAttribute("formId",formId);
		return "app/workflow/formtype/formUseView";
	}

	@RequestMapping("/dataPicker")
	public String dataPicker(HttpServletRequest reques) {
		return "app/workflow/formtype/data_picker";
	}


	/**
	 *
	 * @Createby 韩东堂
	 * @description 根据分类获取此分类下的所有表单
	 * @param sortId 所属分类Id
	 * @return
	 */
	@RequestMapping("/formlistbysort")
	@ResponseBody
	public FlowFormWrappers formBysort(Integer sortId){
		return flowFormService.getFormBySortId(sortId);
	}



	@RequestMapping("/allformlist")
	@ResponseBody
	public FlowFormWrappers formByAll(HttpServletRequest request){
		//return flowFormService.getFormByAll();
		return flowFormService.getFormByDept(request);
	}
	/**
	 * Created by:   韩东堂
	 * date:   2017/5/16 10:09
	 * description:   模糊搜索（根据表单名称）
	 * @param searchValue 搜索关键字
	 * @return
	 */
	@RequestMapping("/formBySearch")
	@ResponseBody
	public FlowFormWrappers formBySearch(String searchValue,Integer sortId){
		return flowFormService.seachForm(searchValue,sortId);
	}


	/**
	 * Created by:   韩东堂
	 * date:   2017/5/16 10:47
	 * description:   新建表单（根据表单名称）
	 * @param formName 表单名称
	 * @param deptId   部门Id
	 * @param formSort 表单分类Id
	 * @param file 其他预留信息（导入的时候使用）
	 * @return
	 */
	@RequestMapping("/newForm")
	@ResponseBody
	public void newForm(String formName, Integer deptId, Integer formSort, @RequestParam(name = "file",required = false) MultipartFile file,
						HttpServletRequest request,HttpServletResponse response){

		BaseWrapper wrapper =new BaseWrapper();
		if(file!=null){
			InputStream in=null;
			try{
				String fileSuffix =file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1).toUpperCase();
				StringBuilder sb = new StringBuilder();
				if(!StringUtils.checkNull(fileSuffix) ){
					if(fileSuffix.equals("TXT") || fileSuffix.equals("HTM") || fileSuffix.equals("HTML")){
						in =file.getInputStream();
						BufferedReader reader = new BufferedReader(new InputStreamReader(in,"utf-8"));

						String line = null;
						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						wrapper =flowFormService.newForm(formName,deptId,formSort,sb.toString());
					}else{
						wrapper.setFlag(false);
						wrapper.setMsg("导入类型不正确,请选择正确的导入类型!");
					}
					//String code = EncodeUtil.getEncode(sb,false);

				}else{
					wrapper.setFlag(false);
					wrapper.setMsg("导入类型不正确,请选择正确的导入类型!");
				}
			}catch (Exception e){
				e.printStackTrace();
				wrapper.setFlag(false);
				wrapper.setMsg("文件读取异常");
			}finally {
				try{
					if(in!=null){
						in.close();
					}
				}catch (Exception p){
					p.printStackTrace();
					wrapper.setFlag(false);
					wrapper.setMsg("文件读取异常");
				}
			}
		}else{
			wrapper =flowFormService.newForm(formName,deptId,formSort,"");
		}
		response.setContentType("text/html; charset=utf-8");
		try {
			ServletOutputStream servletOutputStream = response.getOutputStream();
			OutputStreamWriter ow = new OutputStreamWriter(servletOutputStream,"UTF-8");
			ow.write(JSONObject.toJSONString(wrapper));
			ow.flush();
			ow.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	/**
	 * Created by:   韩东堂
	 * date:   2017/5/16 15:47
	 * description:   更新表单（根据表单id）
	 * @param formId  表单Id
	 * @param formName 表单名称
	 * @param deptId  部门Id
	 * @param formSort 分类Id

	 * @return
	 */
	@RequestMapping("/updateForm")
	@ResponseBody
    public BaseWrapper updateForm(Integer formId,String formName,Integer deptId,Integer formSort,@RequestParam(name = "file",required = false) MultipartFile file){
		BaseWrapper wrapper =new BaseWrapper();
		if(file!=null){
			InputStream in=null;
			BufferedReader reader =null;
			try{
				String fileSuffix =file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1).toUpperCase();

				StringBuilder sb = new StringBuilder();
				if(!StringUtils.checkNull(fileSuffix) ){
					if(fileSuffix.equals("TXT")){
						in =file.getInputStream();
						 reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));

						String line = null;
						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
					}else if(fileSuffix.equals("HTM") || fileSuffix.equals("HTML")){
						in =file.getInputStream();
						 reader = new BufferedReader(new InputStreamReader(in,"UTF-8"));

						String line = null;
						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
					}
					wrapper=flowFormService.updateForm(formId,formName,deptId,formSort,sb.toString());
				}else{
					wrapper.setFlag(false);
					wrapper.setMsg("导入类型不正确,请选择正确的导入类型!");
				}
			}catch (Exception e){
				e.printStackTrace();
				wrapper.setFlag(false);
				wrapper.setMsg("文件读取异常");
			}finally {
				try{
					if(in!=null){
						in.close();
					}
					if(reader!=null){
						reader.close();
					}
				}catch (Exception p){
					p.printStackTrace();
					wrapper.setFlag(false);
					wrapper.setMsg("文件读取异常");
				}
			}
		}else{
			wrapper=flowFormService.updateForm(formId,formName,deptId,formSort,"");
		}


		return wrapper;
	}
//保存表单
	@RequestMapping("/updateFormType")
	@ResponseBody
	public BaseWrapper updateFormType(Integer formId,String formName,Integer deptId,Integer formSort,String printModel,Integer itemMax,String script,String css){
		return flowFormService.updateFormType(formId,formName,deptId,formSort,printModel,itemMax,script,css);
	}

	/**
	 * Created by:   韩东堂
	 * date:   2017/5/17 15:58
	 * description:   更新表单（根据表单id）
	 * @param formId  表单Id
	 * @return
	 */
	@RequestMapping("/deleteForm")
	@ResponseBody
	public BaseWrapper deleteForm(Integer formId){
		return flowFormService.deleteForm(formId);
	}

	@RequestMapping(value = "qureyCtrl",produces = {"application/json;charset=UTF-8"})
	@ResponseBody
	public  ToJson<TMacroCtrl> qureyCtrl(String controlId,String option,HttpServletRequest request,Integer fromId,Integer flowId,
										 String runId, String prcsId, String flowPrcs,String signlock,String PRCS_ID,String FLOW_PRCS,String sql,String sqlList){
		String company="xoa" + (String) request.getSession().getAttribute(
				"loginDateSouse");
	    ContextHolder.setConsumerType(company);
		return flowFormTypeService.qureyCtrl(controlId,option,request,fromId,flowId,runId,prcsId,flowPrcs,company,signlock,PRCS_ID,FLOW_PRCS,sql,sqlList);
	}

	/**
	 * Created by:   韩东堂
	 * date:   2017/8/9 14:08
	 * description:   表单（根据表单id）
	 * @param formId  表单Id
	 * @return
	 */
     @RequestMapping("/outForm")
	 @ResponseBody
	 public void outForm(HttpServletRequest request, HttpServletResponse response,Integer formId){
		 response.setCharacterEncoding("UTF-8");
		 response.setContentType("multipart/form-data");
		 ToJson toJson =flowFormTypeService.qureyItemMax(formId);
		 OutputStream os=null;
		 try {
			 if(toJson.isFlag()){
				 FlowFormType flowFormType=(FlowFormType)toJson.getObject();
				 if(flowFormType!=null){
				 	String fileName =flowFormType.getFormName()+".html";
					 String userAgent = request.getHeader("User-Agent").toUpperCase();
					 if (userAgent.contains("MSIE") || userAgent.contains("TRIDENT") ||userAgent.contains("QTWEBENGINE")) {
						 // win10 ie edge 浏览器 和其他系统的ie
						 fileName = URLEncoder.encode(fileName, "UTF-8");
					 } else if (userAgent.contains("MOZILLA")) {//google,火狐浏览器
						 fileName = new String(fileName.getBytes(), "ISO8859-1");
					 }else {
						 // fe
						 fileName = new String(fileName.getBytes("iso-8859-1"), "UTF-8");
					 }
					 response.setHeader("Content-Disposition",
							 "attachment;fileName=" + fileName);
					 os = response.getOutputStream();
					 os.write(flowFormType.getPrintModel().getBytes("UTF-8"));

				 }
				 os.close();
			 }
		 }catch (Exception e){
		 	e.printStackTrace();
			 if(os!=null){
				 try{
					 os.close();
				 }catch (Exception p){
					 p.printStackTrace();
				 }
			 }
		 }
	 }

	/**
	 * 编辑会签意见（根据权限）
	 * 作者：王禹萌
	 * 时间：2018-07-03 11：20
	 * @param feedId
	 * @return
	 */
	@RequestMapping("/updateContent")
	@ResponseBody
	public BaseWrapper updateContent(Integer feedId,Integer signLook,String content){
		return flowFormTypeService.updateContent(feedId,signLook,content);
	}

	/**
	 * 删除会签意见（根据权限）
	 * 作者：王禹萌
	 * 时间：2018-07-03 13：10
	 * @param feedId
	 * @return
	 */
	@RequestMapping("/deleteContent")
	@ResponseBody
	public BaseWrapper deleteContent(Integer feedId) {
		return flowFormTypeService.deleteContent(feedId);
	}


	/**
	 * 根据flowId获取表单数据
	 */
	@RequestMapping("/getForm")
	@ResponseBody
	public AjaxJson getForm(Integer flowId) {
		return flowFormTypeService.getForm(flowId);
	}

	/**
	 * 	修改移动端工作流表单字段排序
	 * @param mobileDataSort	手机端字段排序
	 * @param formId		表单编号
	 * @param request
	 * @return
	 */
	@RequestMapping("/updateMobileDataSort")
	@ResponseBody
	public AjaxJson updateMobileDataSort(String mobileDataSort,Integer formId,HttpServletRequest request) {
		return flowFormTypeService.updateMobileDataSort(mobileDataSort,formId);
	}

	/**
	 * 获取移动端工作流表单字段排序
	 * @param formId  表单编号
	 * @param request
	 * @return
	 */
	@RequestMapping("/getMobileDataSort")
	@ResponseBody
	public AjaxJson getMobileDataSort(Integer formId,HttpServletRequest request) {
		return flowFormTypeService.getMobileDataSort(formId);
	}
}
